package com.rzj.sys_lab_assistant.controller;

import com.alibaba.fastjson.JSONObject;
import com.rzj.sys_lab_assistant.entity.WxUser;
import com.rzj.sys_lab_assistant.utils.WeChatUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * @program: sys_lab_assistant
 * @description: 用于测试练习前后端交互
 * @author: 作者
 * @create: 2021-08-06 11:13
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Value("wx2cb4bea5aec0335b")
    public String appId;
    @Value("a5b7a599a4acbefbb1bfc786c0848554")
    public String secret;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(@RequestBody WxUser user){
        String code = user.getCode();
        JSONObject object=new JSONObject();
        if(code == "" || "".equals(code)){
            object.put("code",300);
            object.put("msg","code不能为空!");
            return object;
        }
        else {
            //微信接口服务,通过调用微信接口服务中jscode2session接口获取到openid和session_key
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            String str = WeChatUtil.httpRequest(url, "GET", null); //调用工具类解密
            JSONObject jsonObject=JSONObject.parseObject(str);
            String openid = (String) jsonObject.get("openid");
            if(openid != null && !"".equals(openid)){
                //登录成功
                WxUser userVo=new WxUser();
                userVo.setNickName(user.getNickName());
                userVo.setAvatarUrl(user.getAvatarUrl());
                userVo.setOpenId(openid);
                userVo.setGender(user.getGender());
                userVo.setFirstLoginTime(new Date(System.currentTimeMillis()));
                userVo.setLastLoginTime(new Date(System.currentTimeMillis()));
                // 进行数据库操作 保存用户信息。
                System.out.println("userVo==>"+userVo.toString());

                object.put("code",200);
                object.put("msg","登录成功!");
                object.put("userInfo",userVo);
                return object;
            }else {
                object.put("code",400);
                object.put("msg","未知错误，请重试!");
                return object;
            }
        }
    }

}
